package com.sumainfor.pc.epc.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import com.sumainfor.common.Constants;
import com.sumainfor.common.entity.MoSupplierObject;
import com.sumainfor.common.exception.TCException;
import com.sumainfor.common.util.*;
import com.sumainfor.common.utlis.ComUtils;
import com.sumainfor.common.utlis.MoSupplierObjectUtil;
import com.sumainfor.common.utlis.ParamsCommon;
import com.sumainfor.pc.epc.dao.BuyerManageMapper;
import com.sumainfor.pc.epc.dao.StockManageMapper;
import com.sumainfor.pc.epc.dao.SupplierManageMapper;
import com.sumainfor.pc.epc.feign.GetUserInfoFeign;
import com.sumainfor.pc.epc.service.StockManageService;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Author PuaChen
 * 备件管理
 * @Create 2018-11-16 12:08
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class StockManageServiceImpl implements StockManageService {
    @Autowired
    private BuyerManageMapper buyerManageMapper;

    @Autowired
    private StockManageMapper stockManageMapper;

    @Autowired
    private GetUserInfoFeign userInfoFeign;

    @Autowired
    private SupplierManageMapper supplierManageMapper;

    @Autowired
    private ComUtils comUtils;

    /**
     * 获取下拉列表筛选条件 -> 领用人
     *
     * @return
     */
    @Override
    public JsonResult getSelectComponentData() {
        List<String> ids = stockManageMapper.selectTypeForPeople();
        if (ids.isEmpty()) {
            return JsonResult.success(Lists.newArrayList());
        }
        JsonResult<List<Map<String, Object>>> userInfo = userInfoFeign.getUserInfo(ids);
        return JsonResult.success(userInfo.getResult().stream().map(item -> CustomMap.create("userId", MapUtils.getInteger(item, "user_id"))
                .put("username", MapUtils.getString(item, "username")))
                .collect(Collectors.toList()));
    }

    /**
     * 获取备件领用单的列表数据
     *
     * @param page   分页
     * @param params 筛选条件
     * @return
     */
    @Override
    public JsonResult getStockDataList(Page page, Map<String, Object> params) {
        IPage<Map<String, Object>> data = stockManageMapper.selectListData(page, params);
        List<String> ids = new ArrayList<>(1);
        for (Map<String, Object> map : data.getRecords()) {
            ids.add(MapUtils.getString(map, "SysUserId"));
        }
        if (ids.isEmpty()) {
            return JsonResult.success(Lists.newArrayList());
        }
        //请求 Feign 获取数据
        JsonResult<List<Map<String, Object>>> result = userInfoFeign.getUserInfo(ids);
        if (!result.isSuccess()) {
            return JsonResult.error("获取列表用户信息失败");
        }
        //组装数据
        for (Map<String, Object> map : data.getRecords()) {
            for (Map<String, Object> item : result.getResult()) {
                if (MapUtils.getString(map, "SysUserId").equals(MapUtils.getString(item, "user_id"))) {
                    map.put("deptName", MapUtils.getString(item, "deptName"));
                    map.put("userName", MapUtils.getString(item, "username"));
                    map.put("phone", MapUtils.getString(item, "mobile"));
                    break;
                }
            }
        }
        return JsonResult.success(data);
    }

    /**
     * 获得 领用单出库操作的 基本商品数据
     *
     * @param stockId
     * @return
     */
    @Override
    public JsonResult getStockActionInfo(String stockId) {
        List<Map<String, Object>> data = stockManageMapper.getStockActionInfo(stockId);
        for (Map<String, Object> map : data) {
            Integer sum = MapUtils.getInteger(map, "RecNumber", 0);
            Integer doneCount = MapUtils.getInteger(map, "DoneNumber", 0);
            map.put("ComType", ShopTypeSelectUtil.selectShopTypeById(MapUtils.getString(map, "ComType")));
            String monad = stockManageMapper.getMonadBySpeId(MapUtils.getString(map, "ComSpeId"));
            map.put("monad", monad);
            if (sum.equals(doneCount)) {
                //出库已经完成了 进行查询出库记录的操作
                List<Map<String, Object>> logs = stockManageMapper.getStockOutLog(MapUtils.getString(map, "id"));
                map.put("outLogs", logs);
                if (!logs.isEmpty()) {
                    map.put("SupName", logs.get(0).get("SupName"));
                    map.put("ComBrand", logs.get(0).get("ComBrand"));
                    map.put("ComSpeMoName", logs.get(0).get("ComSpeMoName"));
                }
                //领用状态：已领用
                map.put("doneState", 1);
            } else {
                //领用状态：待领用
                map.put("doneState", 0);
            }
            List<Map<String, Object>> list = buyerManageMapper.getBrandString(MapUtils.getString(map, "ComSpeId"));
            map.put("brandList", list);
        }
        return JsonResult.success(data);
    }

    /**
     * 备件领用单的出库操作
     *
     * @param dataList
     * @return
     */
    @Override
    public JsonResult outStockShopAction(List<Map<String, Object>> dataList) {
        for (Map<String, Object> map : dataList) {
            String[] feilds = {"id", "ComSpeMoId", "SupId", "supName", "moName", "doneCount", "RecId"};
            if (!FieldCheckUtil.isMapFieldNotNull(map, feilds)) {
                throw new TCException("参数不完整");
            }
            String id = MapUtils.getString(map, "id");
            String recId = MapUtils.getString(map, "RecId");
            String moId = MapUtils.getString(map, "ComSpeMoId");
            String supId = MapUtils.getString(map, "SupId");

            String supName = MapUtils.getString(map, "supName");
            String brandName = stockManageMapper.getBrandNameByMoId(moId);
            if (StringUtils.isBlank(brandName)) {
                throw new TCException("没有查询到品牌的名称");
            }
            String moName = MapUtils.getString(map, "moName");
            Integer doneCount = MapUtils.getInteger(map, "doneCount");

            //先查询这个详情数据
            Map<String, Object> info = stockManageMapper.getReceiveInfoById(Integer.parseInt(id));
            if (MapUtils.isEmpty(info)) {
                throw new TCException("不存在这个领用单商品");
            }
            int sumCount = MapUtils.getIntValue(info, "RecNumber");
            int doneNumber = MapUtils.getIntValue(info, "DoneNumber");
            if (doneCount == null || doneCount == 0 || sumCount < (doneNumber + doneCount)) {
                throw new TCException("出库数量异常");
            }

            //进行出库之后减少 库存数量
            Map<String, Object> moData = buyerManageMapper.selectComMoOne(moId);
            if (moData == null) {
                throw new TCException("出库异常,商品型号不存在");
            }
            List<MoSupplierObject> moSupplierList = MoSupplierObjectUtil.convertJsonToList(MapUtils.getString(moData, "supplier"));
            if (moSupplierList.isEmpty()) {
                throw new TCException("出库异常,商品型号没有供应商列表");
            }
            MoSupplierObject moSupplierObject = MoSupplierObjectUtil.selectSupplierById(moSupplierList, supId);
            if (moSupplierObject == null) {
                throw new TCException("出库异常,没有这个供应商");
            }

            BigDecimal sum = (BigDecimal) MapUtils.getObject(info, "PriceSum", new BigDecimal(0));
            sum = sum.add(new BigDecimal(Arith.mul(moSupplierObject.getPrice().doubleValue(), Double.valueOf(doneCount))));
            int row = stockManageMapper.updateStockInfo(ParamsCommon.commonUpdateParms(CustomMap.create("RecId", recId)
                    .put("id", id)
                    .put("ComSpeMoId", moId)
                    .put("SupId", supId)
                    .put("PriceSum", sum)
                    .put("SignPrice", moSupplierObject.getPrice())
                    .put("DoneNumber", (doneNumber + doneCount)))
            );
            if (row <= 0) {
                throw new TCException("出库异常,操作失败");
            }
            //操作成功了 进行插入log记录
            row = stockManageMapper.insertOutStockInfoLog(ParamsCommon.commonInsertParms(CustomMap.create("RecInfoId", id)
                    .put("SupName", supName)
                    .put("ComBrand", brandName)
                    .put("ComSpeMoName", moData.get("ComSpeMoName"))
                    .put("OutNumber", doneCount))
            );
            if (row <= 0) {
                throw new TCException("插入出库记录异常,操作失败");
            }


            //原库存数
            int oldCount = moSupplierObject.getStoreCount();
            moSupplierObject.subStoreCount(doneCount);
            //更新型号表信息
            row = buyerManageMapper.updateShopForMo(ParamsCommon.commonUpdateParms(CustomMap.create("ComSpeMoId", moId)
                    .put("supplier", MoSupplierObjectUtil.toJson(moSupplierList))
                    .put("Stock", MapUtils.getInteger(moData, "Stock") - doneCount)
            ));
            if (row <= 0) {
                throw new TCException("更新商品出库数量,操作失败");
            }
            //现在的库存数
            int currentCount = moSupplierObject.getStoreCount();
            //添加备件出库的记录
            IPage<Map<String, Object>> page = stockManageMapper.selectListData(new Page(), CustomMap.create("recId", recId));
            if (page.getRecords() == null && page.getRecords().isEmpty()) {
                throw new TCException("获取领用单主表出现异常");
            }

            //1.构建数据参数
            CustomMap logOutMap = CustomMap.create("ComOutId", UUIDUtils.generatePrefixUuid("OutLog"))
                    .put("ComOutType", 1)
                    .put("SourceId", recId)
                    .put("SysUserId", page.getRecords().get(0).get("SysUserId"))
                    .put("ComSpeMoId", moId)
                    .put("SupId", supId)
                    //原来库存数量
                    .put("RawInventory", oldCount)
                    //出库存数量
                    .put("ComInventory", doneCount)
                    //现在库存数量
                    .put("CasInventory", currentCount);
            ParamsCommon.commonInsertParms(logOutMap, getClass());
            //2. 数据库插入
            row = stockManageMapper.insertStockMainWriteOutLog(logOutMap);
            if (row <= 0) {
                throw new TCException("创建备件出库记录失败");
            }


            //判断是否领用单全部领用完成
            int count = stockManageMapper.selectNotDoneCount(MapUtils.getString(info, "RecId"));
            if (count == 0) {
                //进行更新的操作
                row = stockManageMapper.updateRecMain(ParamsCommon.commonUpdateParms(CustomMap.create("RecId", MapUtils.getString(info, "RecId"))
                        .put("IfState", 2), getClass()));
                if (row <= 0) {
                    throw new TCException("更新主表状态完成,操作失败");
                }
            }

        }
        return JsonResult.success("操作成功");
    }

    /**
     * 获取备件库存列表上筛选条件的数据
     *
     * @return data:{
     * sort:{},
     * shopName:{},
     * brandName:{}
     * }
     */
    @Override
    public JsonResult getStockStoreListHeadType() {
        List<Map<String, Object>> sort = Lists.newArrayList();
        List<Map<String, Object>> shopName = Lists.newArrayList();
        List<Map<String, Object>> brandName = Lists.newArrayList();

        for (Map<String, Object> map : stockManageMapper.getShopTypes("ComBrand")) {
            brandName.add(CustomMap.create("id", map.get("ComId"))
                    .put("name", map.get("ComBrand")));
        }

        for (Map<String, Object> map : stockManageMapper.getShopTypes("ComName")) {
            shopName.add(CustomMap.create("id", map.get("ComId"))
                    .put("name", map.get("ComName")));
        }

        Set<Map.Entry<String, Object>> entries = Constants.ShopTypeConst.TYPE_MAP.entrySet();
        for (Map.Entry<String, Object> entry : entries) {
            sort.add(CustomMap.create("name", entry.getValue()).put("id", entry.getKey()));
        }
        return JsonResult.success(CustomMap.create("sort", sort)
                .put("shopName", shopName)
                .put("brandName", brandName)
        );
    }

    /**
     * 获取备件库存列表数据
     *
     * @param params sort 大类别 1|2
     *               shopName 商品名称
     *               brandName 商品的品牌
     *               search 模糊查询
     * @return
     */
    @Override
    public JsonResult getStockStoreList(Page page, Map<String, Object> params) {
        IPage<Map<String, Object>> mapIPage = stockManageMapper.selectStockStoreList(page, params);
        for (Map<String, Object> map : mapIPage.getRecords()) {
            map.put("ComTypeName", ShopTypeSelectUtil.selectShopTypeById(MapUtils.getString(map, "ComType")));
            map.put("ComTypeFlag", MapUtils.getString(map, "ComType"));
            List<MoSupplierObject> supList = MoSupplierObjectUtil.convertJsonToList(MapUtils.getString(map, "supplier"));
            //总状态
            boolean isWarning = false;
            if (!supList.isEmpty()) {
                for (MoSupplierObject mo : supList) {
                    if (mo.isWarning()) {
                        isWarning = true;
                        break;
                    }
                }
            }
            map.remove("supplier");
            map.put("isWarning", isWarning);
            if (!FieldCheckUtil.isMapFieldNotNull(map, "instm")) {
                map.put("instm", map.get("ComCreate"));
            }
            map.remove("ComCreate");
            DateUtils.formatDateByMap(map);
        }
        //返回数据
        return JsonResult.success(mapIPage);
    }

    /**
     * 停用或者 开启一个 型号商品
     *
     * @param moId
     * @param state 状态 0 或者 1
     * @return
     */
    @Override
    public JsonResult setDisableOrEnableForMo(String moId, Integer state) {
        if (!Objects.equals(state, 1) && !Objects.equals(state, 0)) {
            return JsonResult.error("不存在的状态");
        }

        Map<String, Object> mainOne = stockManageMapper.getShopMainOne(moId);
        if (MapUtils.isNotEmpty(mainOne)) {
            int i = stockManageMapper.updateShopMainByComId(moId, state);
            return i <= 0 ? JsonResult.error("操作失败") : JsonResult.success();
        }

        int row = buyerManageMapper.updateShopForMo(CustomMap.create("delfg", state)
                .put("ComSpeMoId", moId));
        return row <= 0 ? JsonResult.error("操作失败") : JsonResult.success();
    }

    /**
     * 修改 商品型号的基本信息
     *
     * @param params
     * @return
     */
    @Override
    public JsonResult updateStockForMo(Map<String, Object> params) {
        Map<String, Object> parms = ParamsCommon.commonUpdateParms(CustomMap.create("ComSpeMoId", params.get("ComSpeMoId"))
                .put("ComSpeMoName", params.get("ComSpeMoName"))
                .put("Monad", params.get("Monad"))
                .put("Warranty", params.get("Warranty"))
        );
        //判断ErrorCount 不等于空的时候
        if (MapUtils.getInteger(params, "errorCount") != null) {
            Map<String, Object> map = buyerManageMapper.selectComMoOne(MapUtils.getString(params, "ComSpeMoId"));
            List<MoSupplierObject> supList = MoSupplierObjectUtil.convertJsonToList(MapUtils.getString(map, "supplier"));
            for (MoSupplierObject mo : supList) {
                mo.setErrorCount(MapUtils.getIntValue(params, "errorCount"));
            }
            //保存这个操作
            parms.put("supplier", MoSupplierObjectUtil.toJson(supList));
        }
        int row = buyerManageMapper.updateShopForMo(parms);
        return row <= 0 ? JsonResult.error("修改失败") : JsonResult.success();
    }


    /**
     * 获得 这个 商品型号的基本信息详情
     *
     * @param moId
     * @return
     */
    @Override
    public JsonResult getShopForMoInfo(String moId) {
        Map<String, Object> map = stockManageMapper.getShopMoForInfos(moId);
        if (map == null || map.isEmpty()) {
            return JsonResult.error("没有这个商品型号信息");
        }
        Integer errorCount = null;
        List<MoSupplierObject> supList = MoSupplierObjectUtil.convertJsonToList(MapUtils.getString(map, "supplier"));
        if (!supList.isEmpty()) {
            errorCount = supList.get(0).getErrorCount();
        }
        //预警数
        map.put("errorCount", errorCount);
        map.put("ComType", ShopTypeSelectUtil.selectShopTypeById(MapUtils.getString(map, "ComType")));
        map.put("supplier", supList.stream().map(item -> {
            Map<String, Object> supMap = buyerManageMapper.getSupplierById(item.getSupplierId());
            CustomMap data = ObjectUtil.convertObjectToMap(item);
            if (supMap != null) {
                data.put("supName", supMap.get("UnitName"));
            }
            return data;
        }).collect(Collectors.toList()));
        return JsonResult.success(map);
    }


    /**
     * 获得备件详情中的出入库记录信息
     * 入库 参数：
     * type: (2)，
     * supId： 供应商的ID
     * date：时间long
     * moId:型号的id
     * ---
     * 出库 参数
     * type: (1)，
     * userId： 用户的ID
     * date：时间long
     * moId:型号的id
     *
     * @param params
     * @return
     */
    @Override
    public JsonResult getShopMoForOutOrInLogs(Page page, Map<String, Object> params) {
        //获取类目
        Integer type = MapUtils.getInteger(params, "type");
        if (Objects.equals(type, 1)) {
            //这个是出库的
            IPage<Map<String, Object>> outData = stockManageMapper.selectStoreOutputList(page, params);
            if (outData.getRecords().isEmpty()) {
                return JsonResult.success(outData);
            }
            //获得名字获得部门名字
            Set<String> idArr = Sets.newHashSet();
            for (Map<String, Object> map : outData.getRecords()) {
                idArr.add(MapUtils.getString(map, "SysUserId"));
            }
            JsonResult<List<Map<String, Object>>> resInfos = userInfoFeign.getUserInfo(idArr);
            if (!resInfos.isSuccess()) {
                return JsonResult.error("获取用户信息失败");
            }
            for (Map<String, Object> map : outData.getRecords()) {
                for (Map<String, Object> item : resInfos.getResult()) {
                    if (MapUtils.getString(map, "SysUserId").equals(MapUtils.getString(item, "user_id"))) {
                        map.put("username", item.get("username"));
                        map.put("deptName", item.get("deptName"));
                    }
                }
            }
            //数据拼接完毕
            return JsonResult.success(outData);
        } else {
            //这个是入库的
            return JsonResult.success(stockManageMapper.selectStoreInputList(page, params));
        }
    }


    /**
     * 获得备件详情出入库记录 领用人筛选条件接口
     * data:[
     * {
     * name:"张三",
     * id:1
     * }
     * ]
     *
     * @param moId
     * @param type 1 是获得领用人 2 是获得供应商的
     * @return
     */
    @Override
    public JsonResult getShopMoForOutOrInGotoTypeData(String moId, String type) {
        if (type.equals("1")) {
            // 获得出库的 领用人数据
            List<String> peopleIds = stockManageMapper.selectStockOutLogGetPeopleId(moId);
            if (peopleIds.isEmpty()) {
                return JsonResult.success();
            }
            JsonResult<List<Map<String, Object>>> userInfo = userInfoFeign.getUserInfo(peopleIds);
            if (!userInfo.isSuccess()) {
                return JsonResult.error("获取失败");
            }
            List<Map<String, Object>> result = userInfo.getResult();
            return JsonResult.success(result.stream().map(item -> CustomMap.create("id", item.get("user_id"))
                    .put("name", item.get("username"))).collect(Collectors.toList()));
        } else {
            //获得 入库 供应商的数据
            return JsonResult.success(stockManageMapper.selectStockInputLogSupName(moId));
        }

    }

    ///////////////////////////////////////////////////////////////////////////
    // 商品的新增逻辑代码
    ///////////////////////////////////////////////////////////////////////////

    /**
     * 返回添加商品的时候 初始化下拉框的数据
     * -- 所属类型
     * {
     * "key":1,
     * "value":"电器"
     * }
     *
     * @return
     */
    @Override
    public JsonResult getInitSelectComponentDataForShopType() {
        List<CustomMap> list = Lists.newArrayList();
        for (Map.Entry<String, Object> entry : Constants.ShopTypeConst.TYPE_MAP.entrySet()) {
            list.add(CustomMap.create("id", entry.getKey())
                    .put("name", entry.getValue()));
        }
        return JsonResult.success(list);
    }

    /**
     * 返回添加商品的时候 初始化下拉框的数据
     * -- 根据所属类型返回商品的名称
     *
     * @return
     */
    @Override
    public JsonResult getInitSelectComponentDataForShopNames(String typeId, Boolean isIcon) {
        List<Map<String, Object>> list = stockManageMapper.selectShopNames(typeId);
        if (isIcon != null && isIcon) {
            return JsonResult.success(list);
        }
        return JsonResult.success(list.stream().map(iv -> MapUtils.getString(iv, "ComName")).collect(Collectors.toList()));
    }

    /**
     * 返回添加商品的时候 初始化下拉框的数据
     * -- 根据商品的名称返回商品的品牌
     *
     * @return
     */
    @Override
    public JsonResult getInitSelectComponentDataForShopBrand(String shopName) {
        return JsonResult.success(stockManageMapper.selectShopForBrandByShopName(shopName));
    }


    /**
     * 返回添加商品的时候 初始化下拉框的数据
     * -- 根据商品的编号返回这个商品所有的规格名称和编号
     *
     * @return
     */
    @Override
    public JsonResult getInitSelectComponentDataForSpe(String shopId) {
        return JsonResult.success(stockManageMapper.selectSpeByShopId(shopId));
    }


    /**
     * 返回添加商品的时候 初始化下拉框的数据
     * -- 根据商品规格编号返回这个规格的所有对应的型号
     *
     * @return
     */
    @Override
    public JsonResult getInitSelectComponentDataForMo(String speId) {
        List<Map<String, Object>> dataList = stockManageMapper.selectMoBySpeId(speId);
        for (Map<String, Object> map : dataList) {
            List<MoSupplierObject> supplier = MoSupplierObjectUtil.convertJsonToList(MapUtils.getString(map, "supplier"));

            map.put("SupList", supplier.stream().map(su -> ObjectUtil.convertObjectToMap(su)
                    .put("supName", MapUtils.getString(supplierManageMapper.getSupplierOne(su.getSupplierId()), "UnitName"))).collect(Collectors.toList()));
        }
        return JsonResult.success(dataList);
    }

    /**
     * 返回添加商品的时候 初始化下拉框的数据
     * -- 返回这个商品的所有的单位
     *
     * @return
     */
    @Override
    public JsonResult getInitSelectComponentDataForUnit(String speId) {
        return JsonResult.success(stockManageMapper.selectUnitBySpeId(speId));
    }


    /**
     * 返回添加商品的时候 初始化下拉框的数据
     * -- 根据供应商的类型 返回所有供应商的编号和名称
     *
     * @return
     */
    @Override
    public JsonResult getInitSelectComponentDataForSup(String supType) {
        return JsonResult.success(stockManageMapper.selectSupList(supType));
    }

    /**
     * 新增商品进行的接口
     *
     * @param params
     * @return
     */
    @Override
    public JsonResult insertShopInfo(Map<String, Object> params) {
        if (ShopTypeSelectUtil.isActivity(MapUtils.getString(params, "type"))) {
            //商品编号
            String comId = MapUtils.getString(params, "ComId");
            //规格编号
            String speId = MapUtils.getString(params, "ComSpeId");

            //构建型号标的数据
            String price = MapUtils.getString(params, "price");
            Integer errorCount = MapUtils.getInteger(params, "errorCount");
            List<String> supIds = (List<String>) MapUtils.getObject(params, "supList");
            if (supIds == null || supIds.isEmpty()) {
                return JsonResult.error("请绑定供应商");
            }

            List<MoSupplierObject> supplier = new ArrayList<>(supIds.size());
            for (int i = 0; i < supIds.size(); i++) {
                MoSupplierObject obj = new MoSupplierObject();
                obj.setSupplierId(supIds.get(i));
                obj.setErrorCount(errorCount);
                obj.setStoreCount(0);
                obj.setPrice(new BigDecimal(price));
                supplier.add(obj);
            }


            //型号数据构建
            CustomMap moBaseData = CustomMap.create("ComSpeMoName", MapUtils.getString(params, "ComSpeMoName"))
                    .put("Monad", MapUtils.getString(params, "Monad"))
                    .put("supplier", MoSupplierObjectUtil.toJson(supplier))
                    .put("Stock", 0)
                    .put("ComSpeMoNotes", MapUtils.getString(params, "ComSpeMoNotes"))
                    .put("Warranty", MapUtils.getString(params, "Warranty"));


            //当是电器的时候
            if (MapUtils.getString(params, "type").equals("1")) {
                moBaseData.put("DeviceType", MapUtils.getInteger(params, "DeviceType", 0));
            } else if (MapUtils.getString(params, "type").equals("4")) {
                //是智能设备的时候
                moBaseData.put("InteType", MapUtils.getInteger(params, "InteType", 0));
            }

            if (StringUtils.isNotBlank(comId) && StringUtils.isNotBlank(speId)) {
                //都不是空的情况下 属于录入新的型号
                //先判断是否存在 这个商品  和 型号
                if (MapUtils.isEmpty(stockManageMapper.getShopMainOne(comId))) {
                    throw new TCException("商品不存在");
                }

                if (MapUtils.isEmpty(stockManageMapper.getSpeDataBySpeId(speId))) {
                    throw new TCException("规格不存在");
                }
                //不做操作
            } else if (StringUtils.isNotBlank(comId) && StringUtils.isBlank(speId)) {
                //先判断是否存在 这个商品  和 型号
                if (MapUtils.isEmpty(stockManageMapper.getShopMainOne(comId))) {
                    throw new TCException("商品不存在");
                }

                //属于录入新的规格和型号
                //1. 构建规格
                if (!FieldCheckUtil.isMapFieldNotNull(params, "ComSpeName")) {
                    return JsonResult.error("请提供规格的名称");
                }
                speId = comUtils.getLocalTrmSeqNumByLook("Spe", Constants.DATA_SOURCE_TCEPC, "tcepc_commodity_spe", "ComSpeId");
                int i = stockManageMapper.insertShopForSpe(ParamsCommon.commonInsertParms(CustomMap.create("ComSpeId", speId)
                        .put("ComId", comId)
                        .put("ComSpeName", MapUtils.getString(params, "ComSpeName")), getClass()));
                if (i <= 0) {
                    return JsonResult.error("新增规格操作失败");
                }
            } else {
                //否则就是属于全新的商品
                comId = comUtils.getLocalTrmSeqNumByLook("Com", Constants.DATA_SOURCE_TCEPC, "tcepc_commodity", "ComId");
                speId = comUtils.getLocalTrmSeqNumByLook("Spe", Constants.DATA_SOURCE_TCEPC, "tcepc_commodity_spe", "ComSpeId");
                String[] filed = {"ComBrand", "ComName", "ComSpeName"};
                if (!FieldCheckUtil.isMapFieldNotNull(params, filed)) {
                    return JsonResult.error("请提供必要的参数");
                }

                CustomMap comDataMap = CustomMap.create();

                //新商品录入商品的图片 Icon
                String comIcon = MapUtils.getString(params, "ComIcon");

                int i = stockManageMapper.insertShopForCom(ParamsCommon.commonInsertParms(comDataMap
                                .put("ComType", MapUtils.getString(params, "type"))
                                .put("ComId", comId)
                                .put("ComBrand", MapUtils.getString(params, "ComBrand"))
                                .put("ComName", MapUtils.getString(params, "ComName"))
                                .put("ComIncon", comIcon)
                        , getClass()));
                if (i <= 0) {
                    return JsonResult.error("新增商品操作失败");
                }

                //新增规格
                i = stockManageMapper.insertShopForSpe(ParamsCommon.commonInsertParms(CustomMap.create("ComSpeId", speId)
                        .put("ComId", comId)
                        .put("ComSpeName", MapUtils.getString(params, "ComSpeName")), getClass()));
                if (i <= 0) {
                    throw new TCException("新增规格操作失败");
                }
            }
            //录入型号
            moBaseData.put("ComSpeId", speId);
            //获取UUID
            String uuid = comUtils.getLocalTrmSeqNumByLook("Mo", Constants.DATA_SOURCE_TCEPC, "tcepc_commodity_spe_mo", "ComSpeMoId");
            moBaseData.put("ComSpeMoId", uuid);
            //进行插入的操作
            int row = stockManageMapper.insertShopForMo(ParamsCommon.commonInsertParms(moBaseData, getClass()));
            if (row <= 0) {
                throw new TCException("新增型号失败");
            }

            //双向绑定这个供应商
            for (int i = 0; i < supIds.size(); i++) {
                Map<String, Object> supplierOne = supplierManageMapper.getSupplierOne(supIds.get(i));
                if (supplierOne == null || supplierOne.isEmpty()) {
                    throw new TCException("找不到供应商信息-" + supIds.get(i));
                }
                String moIds = MapUtils.getString(supplierOne, "ComSpeMoId", "");
                moIds = moIds + uuid + ",";
                supplierOne.put("ComSpeMoId", moIds);
                ParamsCommon.commonUpdateParms(supplierOne, getClass());
                row = supplierManageMapper.updateSupplier(supplierOne);
                if (row <= 0) {
                    throw new TCException("绑定供应商失败");
                }
            }
            return JsonResult.success("操作成功");
        } else {
            //其他费用
            String comId = comUtils.getLocalTrmSeqNumByLook("Com", Constants.DATA_SOURCE_TCEPC, "tcepc_commodity", "ComId");
            int row = stockManageMapper.insertShopForCom(ParamsCommon.commonInsertParms(CustomMap.create("ComId", comId)
                            .put("ComType", MapUtils.getString(params, "type"))
                            .put("ComName", MapUtils.getString(params, "ComName"))
                            .put("ComBrand", MapUtils.getString(params, "ComBrand"))
                            .put("ComPrice", new BigDecimal(MapUtils.getString(params, "price")))
                    , getClass()));
            if (row <= 0) {
                return JsonResult.error("新增失败");
            }
            return JsonResult.success("操作成功");
        }
    }


    ///////////////////////////////////////////////////////////////////////////
    // 单个备件出库和入库的操作
    ///////////////////////////////////////////////////////////////////////////

    /**
     * 单个备件的出库的操作
     *
     * @param params
     * @return
     */
    @Override
    public JsonResult signOutputForStock(Map<String, Object> params) {
        String moId = MapUtils.getString(params, "moId");
        String supId = MapUtils.getString(params, "supId");
        Integer count = MapUtils.getInteger(params, "count");
        String userId = MapUtils.getString(params, "userId");

        //查出来进行库存的减少操作
        Map<String, Object> moMap = buyerManageMapper.selectComMoOne(moId);
        if (moMap == null || moMap.isEmpty()) {
            return JsonResult.error("没有这个商品的信息");
        }
        List<MoSupplierObject> supList = MoSupplierObjectUtil.convertJsonToList(MapUtils.getString(moMap, "supplier"));
        MoSupplierObject mo = MoSupplierObjectUtil.selectSupplierById(supList, supId);
        if (mo == null) {
            return JsonResult.error("供应商不存在");
        }
        int oldCount = mo.getStoreCount();
        mo.subStoreCount(count);
        int curCount = mo.getStoreCount();
        moMap.put("supplier", MoSupplierObjectUtil.toJson(supList));
        moMap.put("Stock", MapUtils.getInteger(moMap, "Stock") - count);
        int i = buyerManageMapper.updateShopForMo(moMap);
        if (i <= 0) {
            return JsonResult.error("出库失败");
        }
        //构建出库数据
        //1.构建数据参数
        CustomMap logOutMap = CustomMap.create("ComOutId", UUIDUtils.generatePrefixUuid("OutLog"))
                .put("ComOutType", 2)
                .put("SysUserId", userId)
                .put("ComSpeMoId", moId)
                .put("SupId", supId)
                //原来库存数量
                .put("RawInventory ", oldCount)
                //出库存数量
                .put("ComInventory ", count)
                //现在库存数量
                .put("CasInventory ", curCount);
        ParamsCommon.commonInsertParms(logOutMap);
        //2. 数据库插入
        int row = stockManageMapper.insertStockMainWriteOutLog(logOutMap);
        if (row <= 0) {
            throw new TCException("创建备件出库记录失败");
        }
        return JsonResult.success("操作成功");
    }


    /**
     * 单个备件的出库 所有领用人的数据
     *
     * @return
     */
    @Override
    public JsonResult getStocketOutPeopleDataList() {
        List<Map<String, Object>> people = userInfoFeign.getRepairPeople();
        if (people == null) {
            return JsonResult.error("错误");
        }
        return JsonResult.success(people);
    }


    /**
     * 单个备件的入库的操作
     *
     * @param params
     * @return
     */
    @Override
    public JsonResult signInputForStock(Map<String, Object> params) {
        String supId = MapUtils.getString(params, "supId");
        String moId = MapUtils.getString(params, "moId");
        Integer count = MapUtils.getInteger(params, "count");

        //查出来进行库存的进行增加操作
        Map<String, Object> moMap = buyerManageMapper.selectComMoOne(moId);
        if (moMap == null || moMap.isEmpty()) {
            return JsonResult.error("没有这个商品的信息");
        }
        List<MoSupplierObject> supList = MoSupplierObjectUtil.convertJsonToList(MapUtils.getString(moMap, "supplier"));
        MoSupplierObject mo = MoSupplierObjectUtil.selectSupplierById(supList, supId);
        if (mo == null) {
            return JsonResult.error("此备件没有绑定这个供应商");
        }
        int oldCount = mo.getStoreCount();
        mo.addStoreCount(count);
        int curCount = mo.getStoreCount();
        moMap.put("supplier", MoSupplierObjectUtil.toJson(supList));
        moMap.put("Stock", MapUtils.getInteger(moMap, "Stock") + count);
        int i = buyerManageMapper.updateShopForMo(ParamsCommon.commonUpdateParms(moMap));
        if (i <= 0) {
            return JsonResult.error("入库失败");
        }

        //进行入库的记录的操作
        String uuid = UUIDUtils.generatePrefixUuid("StockInLog");
        CustomMap logData = CustomMap.create("ComInId", uuid)
                .put("ComSpeMoId", moId)
                .put("SupId", supId)
                .put("RawInventory", oldCount)
                .put("ComInventory", count)
                .put("CasInventory", curCount);
        ParamsCommon.commonInsertParms(logData, getClass());
        int row = buyerManageMapper.insertStoreInPutLog(logData);
        if (row <= 0) {
            throw new TCException("商品入库添加日志出现异常,操作失败");
        }
        return JsonResult.success("操作成功");
    }


    /**
     * 查询商品主表的名称和图片
     *
     * @param ids
     * @return
     */
    @Override
    public JsonResult selectShopNameAndIcon(List<String> ids) {
        return JsonResult.success(stockManageMapper.selectShopNameAndIconByIds(ids));
    }


    /**
     * 根据房源配置主编号查询房源配置详表信息
     *
     * @param configId
     * @return
     */
    @Override
    public JsonResult selectConfigInfoByConfigId(String configId) {
        return JsonResult.success(stockManageMapper.selectConfigInfoData(configId));
    }

    /**
     * 获取商品的编号根据房源配置编号 - 公共区域用
     *
     * @param ids
     * @return
     */
    @Override
    public JsonResult selectComIdArrayByConIdList(List<String> ids) {
        return JsonResult.success(stockManageMapper.selectComIdArrayByConIdList(ids));
    }

}
